<?php
namespace org;

class Wechat{
    private $Record = array();

    public function __construct($Token){
        $this->DataAuth($Token) || exit;
        
        if(request()->isGet()){
            exit(request()->get('echostr'));
        }else{
            $Xml = file_get_contents("php://input");
            $Xml = new \SimpleXMLElement($Xml);
            $Xml || exit; 
            foreach($Xml as $k => $v){
                $this->Record[$k] = strval($v);
            }
        }
    }

    private function DataAuth($Token){
        $Time = request()->get('timestamp');
        $Keys = request()->get('nonce');
        $Sign = request()->get('signature');

        $Data = array($Token, $Time, $Keys);

        sort($Data, SORT_STRING);
        
        $Ture = sha1(implode($Data));

        return $Ture === $Sign;
    }

    public function DataGain(){
        return $this->Record;
    }

    public function DataSend($Content, $Type = 'text', $Flag = 0){
        $Time = time();
        
        $this->Record = array('ToUserName' => $this->Record['FromUserName'], 'FromUserName' => $this->Record['ToUserName'], 'CreateTime' => $Time, 'MsgType' => $Type);
        $this->$Type($Content);
        $this->Record['FuncFlag'] = $Flag;
        
        $Xml = new \SimpleXMLElement('<xml></xml>');
        $this->DataXml($Xml, $this->Record);
        
        exit($Xml->asXML());
    }

    private function text($Text){
        $this->Record['Content'] = $Text;
    }
    
    private function music($Music){
        list($Music['Title'], $Music['Description'], $Music['MusicUrl'], $Music['HQMusicUrl']) = $Music;

        $this->Record['Music'] = $Music;
    }

    private function news($News){
        $Array = array();

        foreach($News as $k => $v){
            list($Array[$k]['Title'], $Array[$k]['Description'], $Array[$k]['PicUrl'], $Array[$k]['Url']) = $v;
            if($k >= 9){
                break;
            }
        }

        $this->Record['ArticleCount'] = count($Array);
        $this->Record['Articles'] = $Array;
    }

    private function DataXml($Xml, $Data, $Item = 'item'){
        foreach($Data as $k => $v){
            is_numeric($k) && $k = $Item;
            if(is_array($v) || is_object($v)){
                $Child = $Xml->addChild($k);
                $this->DataXml($Child, $v, $Item);
            }else{
                if(is_numeric($v)){
                    $Child = $Xml->addChild($k, $v);
                }else{
                    $Child = $Xml->addChild($k);
                    $Node = dom_import_simplexml($Child);
                    $Node->appendChild($Node->ownerDocument->createCDATASection($v));
                }
            }
        }
    }

}